﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Coding4Fun.Phone.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using RadarGlobalPro.Class;

namespace RadarGlobalPro.GUIView
{
    public partial class MemberGroupDlg : PhoneApplicationPage
    {
        ContextMenuController myContextMenu;

        ApplicationBarController barControl;

        Status myStatus = new Status();

        string groupid;
        int owner;

        public MemberGroupDlg()
        {
            InitializeComponent();
            InitializeAppllication();
            InitializeContextMenu();
        }
        #region CreateController
        public void InitializeContextMenu()
        {
            myContextMenu = new ContextMenuController();
            myContextMenu.Add("Remove user in group", true, ConextMenuEvent);
            myContextMenu.Add("Agree for join group", true, ConextMenuEvent);
            myContextMenu.Add("Remove request join", true, ConextMenuEvent);
            myContextMenu.Add("Invite to group", true, ConextMenuEvent);
        }
        public void InitializeAppllication()
        {
            barControl = new ApplicationBarController(this.ApplicationBar);

            barControl.AddNewButton("accept all", "/Images/appbar.add.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("remove all", "/Images/appbar.delete.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("refresh", "/Images/appbar.refresh.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("find", "/Images/appbar.feature.search.rest.png", true, ApplicationBarButton_Click);
        }
        #endregion

        #region Load Data All List User
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            myStatus.ShowPopup("Wait for loading user in server ....!!");

            base.OnNavigatedTo(e);
            string myowner;
            if (NavigationContext.QueryString.ContainsKey("groupid"))
            {
                if (NavigationContext.QueryString.TryGetValue("groupid", out groupid))
                {
                    ReloadData();
                }
            }
            if (NavigationContext.QueryString.ContainsKey("owner"))
            {
                if (NavigationContext.QueryString.TryGetValue("owner", out myowner))
                {
                    owner = int.Parse(myowner);
                }
            }
        }
        public void ReloadData()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (groupid != null && groupid != "")
            {
                client.GetListUserInGroupCompleted += (s, args) =>
                {
                    if (args.Result != null)

                        LoadDataInList(args.Result);

                    myStatus.Abort();
                };
                client.GetListUserInGroupAsync(int.Parse(groupid));

                LoadListUser();
            }
        }
        public void LoadDataInList(string Content)
        {

            List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(Content);

            listMember.Items.Clear();
            listWaitJoin.Items.Clear();

            var data = User.DeserializeObject(listdata);

            foreach (User item in data)

                if (item.Status == 1)
                {
                    listMember.Items.Add(item);
                }
                else
                    if (item.Status == 2)
                    {
                        item.TagType = 1;
                        listWaitJoin.Items.Add(item);
                    }

            if (listMember.Items.Count > 0)

                listMember.SelectedIndex = 0;
        }
        public void LoadListUser()
        {
            ListAllUser.ItemsSource = null;

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetListUserCompleted += (s, e) =>
            {
                if (e.Result == null) return;

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(e.Result);

                var data = User.DeserializeObject(listdata,2);

                 List<AlphaKeyGroup<User>> Datasource = AlphaKeyGroup<User>.CreateGroups(data, System.Threading.Thread.CurrentThread.CurrentUICulture,
                    (User user) => { return user.Username; }, true);

                 ListAllUser.ItemsSource = Datasource;
            };

            client.GetListUserAsync(0, 30);
        }
        public void LoadListUser(string szUsername)
        {
            ListAllUser.ItemsSource = null;

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.FindListUserCompleted += (s, e) =>
            {
                if (e.Result == null) return;

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(e.Result);

                var data = User.DeserializeObject(listdata);

                List<AlphaKeyGroup<User>> Datasource = AlphaKeyGroup<User>.CreateGroups(data, System.Threading.Thread.CurrentThread.CurrentUICulture,
                    (User user) => { return user.Username; }, true);

                ListAllUser.ItemsSource = Datasource;

                myStatus.Abort();
            };

            client.FindListUserAsync(szUsername);
        }
        #endregion


        private void ApplicationBarButton_Click(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }

            ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;

            string text = btn.Text.ToLower();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == "accept all")
            {
                client.ChangeStatusGroupCompleted += (s, args) =>
                {
                    MessageBox.Show("You take any all requests");

                    ReloadData();
                };
                client.ChangeStatusGroupAsync(int.Parse(groupid), 1, 2);
            }

            if (text == "remove all")
            {
                client.RemoveLinkerStatusCompleted += (s, args) =>
                {
                    MessageBox.Show("You are removed expired the required");

                    ReloadData();
                };
                client.RemoveLinkerStatusAsync(int.Parse(groupid), 2);
            }

            if (text == "refresh")
            {
                myStatus.ShowPopup("Wait for loading user in server ....!!");

                ReloadData();
            }

            if (text == "find")
            {
                myStatus.ShowPopup("Wait for find user in server ....!!");

                InputPrompt input = new InputPrompt();
                input.Completed += (s, args) =>
                {
                    if (args.Result != null && args.Result != "")

                        LoadListUser(args.Result);
                };
                input.Title = "Find user";
                input.Message = "Input user name you want find :";
                input.Show();
            }

        }

        private void MainPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = MainPivot.SelectedIndex;
            switch (i)
            {
                case 0:
                    barControl.ShowAppBar(false);
                    break;
                case 1:
                    barControl.ShowAppBar(true);
                    barControl.RemoveButtons("accept all", "remove all", "find");
                    barControl.ShowButtons("accept all", "remove all", "refresh");
                    break;
                case 2:
                    barControl.ShowAppBar(true);
                    barControl.RemoveButtons("accept all", "remove all", "refresh");
                    barControl.ShowButtons("find", "refresh");
                    break;
            }
        }

        private void ItemUser_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = ((Grid)sender).DataContext as User;

            if (item != null)
            {
                myContextMenu.RemoveMenuItems();

                myContextMenu.AddControlHandler(sender);

                if (item.TagType == 0)
                {
                    myContextMenu.ShowMenuItems("Remove user in group");
                }
                if (item.TagType == 1)
                {
                    myContextMenu.ShowMenuItems("Agree for join group", "Remove request join");
                }
                if (item.TagType == 2)
                {
                    myContextMenu.ShowMenuItems("Invite to group");
                }

            }
        }
        private void ConextMenuEvent(object sender, EventArgs e)
        {
            
            MenuItem mnitem = (MenuItem)sender;
            string text = mnitem.Header.ToString();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == "Remove user in group")
            {
                if (owner != 1)
                {
                    MessageBox.Show("You are not leader", "Warning!", MessageBoxButton.OK);

                    return;
                }
                ListBoxItem listItem = this.listMember.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    User data = listItem.Content as User;

                    if (data.UserID == Global.UserInfo.UserID)
                    {
                        MessageBoxResult result = MessageBox.Show("You are the leader, if you leave the group, the group will be disbanded", "Are you want leave group?", MessageBoxButton.OKCancel);

                        if (result == MessageBoxResult.OK)
                        {
                            client.RemoveGroupAsync(int.Parse(groupid));

                            client.RemoveGroupCompleted += (s, args) =>
                            {
                                if (args.Result == true)
                                {
                                    MessageBox.Show("You are leave group sucess!");

                                    NavigationService.Navigate(new Uri("/UIView/GroupDlg.xaml"));
                                }
                            };
                        }
                    }
                    else
                    {
                        client.RemoveLinkerCompleted += (s, args) =>
                        {
                            MessageBox.Show(data.Username + " member has been expelled");

                            ReloadData();
                        };

                        client.RemoveLinkerAsync(int.Parse(groupid), data.UserID);
                    }
                }
            }
            if (text == "Agree for join group")
            {
                if (owner != 1)
                {
                    MessageBox.Show("You are not a leader.", "Warning!", MessageBoxButton.OK);
                    return;
                }
                ListBoxItem listItem = this.listWaitJoin.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    User data = listItem.Content as User;

                    client.UpdateLinkerCompleted += (s, args) =>
                    {
                        MessageBox.Show(data.Username + " Members agreed on a group.!");

                        ReloadData();
                    };
                    client.UpdateLinkerAsync(int.Parse(groupid), data.UserID, 0, 1);
                }
            }
            if (text == "Remove request join")
            {
                if (owner != 1)
                {
                    MessageBox.Show("You are not a leader.", "Warning!", MessageBoxButton.OK);
                    return;
                }
                ListBoxItem listItem = this.listWaitJoin.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    User data = listItem.Content as User;

                    client.RemoveLinkerCompleted += (s, args) =>
                    {
                        MessageBox.Show("Delete the request from " + data.Username);


                        ReloadData();
                    };

                    client.RemoveLinkerAsync(int.Parse(groupid), data.UserID);
                }
            }
            if (text == "Invite to group")
            {
                if (owner != 1)
                {
                    MessageBox.Show("You are not a leader.", "Warning!", MessageBoxButton.OK);
                    return;
                }
                User data = mnitem.DataContext as User;

                if (data != null)
                {
                    client.InvateGroupCompleted += (s, args) =>
                    {
                        if (args.Result == true)
                            MessageBox.Show("successfully invited, please wait for the user agrees", "Send invate for user", MessageBoxButton.OK);
                        else
                            MessageBox.Show("Can not invited, maybe this person was in the group", "Send invate for user", MessageBoxButton.OK);
                    };

                    client.InvateGroupAsync(data.UserID, int.Parse(groupid));
                }                
            }
        }
    }
}